import 'package:dio/dio.dart';

void main(List<String> args) {
  // Dio().get("https://geek.itheima.net/v1_0/channels").then((res){
  //   print(res);
  // });
  //使用封装的工具类
  DioUtils().get("channels").then((res){
    print("res------>:$res");
  });
}


//封装一个工具类
class DioUtils{
  final Dio _dio = Dio();
  DioUtils(){
    // _dio.options.baseUrl = "https://geek.itheima.net/v1_0/";
    // _dio.options.connectTimeout = Duration(seconds: 10);//连接超时时间
    // _dio.options.sendTimeout = Duration(seconds: 10);//发送超时时间
    // _dio.options.receiveTimeout = Duration(seconds: 10);//接收超时时间
    //简写..连续赋值的写法
    _dio.options
    ..baseUrl="https://geek.itheima.net/v1_0/"
    ..connectTimeout=Duration(seconds: 10)
    ..sendTimeout=Duration(seconds: 10)
    ..receiveTimeout=Duration(seconds: 10);

    //添加拦截器
    _addInterceptors();
    
  }


  void _addInterceptors(){
    _dio.interceptors.add(InterceptorsWrapper(
      onRequest: (options,handler){
        // handler.reject(error)拦截请求
        //在请求之前做一些事情
        handler.next(options);
      },
      onResponse: (response,handler){
        if(response.statusCode!>=200 && response.statusCode!<=300){
          handler.next(response);//继续传递响应
          return;
        }
        //处理异常
        handler.reject(DioException(
          requestOptions: response.requestOptions,
          response: response,
          message: "状态码${response.statusCode}"
        ));
      },
      onError: (DioException e,handler){
        handler.reject(e);
      }
    ));
  }

//向外暴露一个get方法
get(String url,{Map<String,dynamic>? queryParameters})async{
  try{
    Response response = await _dio.get(url,queryParameters: queryParameters);
    return response.data;
  }on DioException catch(e){
    return e.message;
  }
}
}